package top.yaofengqiao.springcloudsimple.redis.starter.service;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.time.Duration;

/**
 * @author yfq
 * @date 2024/6/7 10:24
 * @description
 */
public class RedisService implements IRedisService {
    private final RedissonClient redissonClient;

    public RedisService(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public <T> void setValue(String key, T value) {
        redissonClient.<T>getBucket(key).set(value);
    }

    @Override
    public <T> void setValue(String key, T value, Duration duration) {
        redissonClient.<T>getBucket(key).set(value, duration);
    }

    @Override
    public <T> T getValue(String key) {
        return redissonClient.<T>getBucket(key).get();
    }

    @Override
    public boolean delete(String key) {
        return redissonClient.getBucket(key).delete();
    }

    @Override
    public boolean exist(String key) {
        return redissonClient.getBucket(key).isExists();
    }

    @Override
    public <T> boolean setNx(String key, T value) {
        return redissonClient.getBucket(key).setIfAbsent(value);
    }

    @Override
    public <T> boolean setNx(String key, T value, Duration duration) {
        return redissonClient.getBucket(key).setIfAbsent(value, duration);
    }

    @Override
    public long getIncrement(String key) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);

        return atomicLong.getAndIncrement();
    }

    @Override
    public void expires(String key, Duration duration) {
        redissonClient.getBucket(key).expire(duration);
    }

    @Override
    public boolean tryLock(String key) {
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock();
    }

    @Override
    public void unLock(String key) {
        RLock lock = redissonClient.getLock(key);
        lock.unlock();
    }

    @Override
    public RLock getLock(String key) {
        return redissonClient.getLock(key);
    }

}
